/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import com.Book;
import com.Cart;
import com.Checker;
import com.DBConnector;
import com.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Nhan
 */
public class centralUnit extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    ArrayList<Cart> selectedItems;

    float getTotal(ArrayList<Cart> items) {
        float total = 0;
        for (Cart item : items) {
            total += item.getNumItem() * item.getPrice();
        }
        return total;
    }

    public void handleAddToCart(HttpServletRequest request, ArrayList<Cart> selectedItems) {

        String id = request.getParameter("bookID");
        if (id != null) {
            if (selectedItems == null) {
                selectedItems = new ArrayList<Cart>();
            }
            Book targetBook = Checker.getBookInfo(id);

            int quantity = 1;
            int indexFound = isAdded(selectedItems, id);

            if (indexFound != -1) {
                //update so luong khi da add roi
                Cart item = selectedItems.get(indexFound);
                int curNumItem = item.getNumItem();
                item.setNumItem(++curNumItem);
                selectedItems.set(indexFound, item);
            } else {
                //them vao shopping cart khi chua dc add
                //int id, String title, String image, String author,
                //String type, int numItem, float price
                selectedItems.add(new Cart(Integer.valueOf(id), targetBook.getTitle(), targetBook.getImage(), targetBook.getAuthor(), targetBook.getType(), quantity, targetBook.getPrice()));
            }

            HttpSession session = request.getSession();
            if (selectedItems != null) {
                session.setAttribute("selectedItems", selectedItems);
            }

        }

    }

    int isAdded(ArrayList<Cart> selectedItems, String id) {
        for (int i = 0; i < selectedItems.size(); i++) {
            String bookID = selectedItems.get(i).getId() + "";
            if (bookID.equals(id)) {
                return i;
            }
        }
        return -1;
    }
    static DBConnector connectObj = new DBConnector();
    static Connection con = connectObj.getCon();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here*/
            String action = request.getParameter("action").trim();
            if (action.equalsIgnoreCase("Login")) {
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");

                User curUser = Checker.checkUser(username, password);

                if (curUser != null) {
                    HttpSession session = request.getSession();
                    String role = curUser.getRole().trim();
                    session.setAttribute("currentUser", curUser);

                    //send redirect to exactly page
                    if (role.equalsIgnoreCase("guest")) {
                        response.sendRedirect("./guest/guestIndex.jsp");
                    } else if (role.equalsIgnoreCase("customer")) {
                        response.sendRedirect("./customer/customerIndex.jsp");
                    } else if (role.equalsIgnoreCase("Manager")) {
                        out.println("manager!");
                        response.sendRedirect("manager/managerIndex.jsp");
                    }

                } else {
                    RequestDispatcher dis = request.getRequestDispatcher("./index.jsp");
                    out.println("<h3>Invalid username or password</h3>");
                    dis.include(request, response);
                }
            } else if (action.equalsIgnoreCase("getSearch")) {
                response.sendRedirect("search.jsp");
            } else if (action.equalsIgnoreCase("search")) {
                RequestDispatcher dis = request.getRequestDispatcher("./search.jsp");
                dis.forward(request, response);
            } else if (action.equalsIgnoreCase("Add To Cart")) {
                HttpSession session = request.getSession();

                ArrayList<Cart> addToCart = (ArrayList<Cart>) session.getAttribute("selectedItems");

                if (addToCart == null) {
                    addToCart = new ArrayList<Cart>();
                }

                handleAddToCart(request, addToCart);

                this.selectedItems = addToCart;

                response.sendRedirect("./search.jsp");

            } else if (action.equalsIgnoreCase("viewCart")) {
                response.sendRedirect("./viewCart.jsp");

            } else if (action.equalsIgnoreCase("gotoHomePage")) {
                HttpSession session = request.getSession();
                User curUser = (User) session.getAttribute("currentUser");
                String role = curUser.getRole().trim();
                session.setAttribute("currentUser", curUser);

                //send redirect to exactly page
                if (role.equalsIgnoreCase("guest")) {
                    response.sendRedirect("./guest/guestIndex.jsp");
                } else if (role.equalsIgnoreCase("customer")) {
                    response.sendRedirect("./customer/customerIndex.jsp");
                } else if (role.equalsIgnoreCase("Manager")) {
                    out.println("manager!");
                    response.sendRedirect("manager/managerIndex.jsp");
                }
            } else if (action.equalsIgnoreCase("viewBook")) {
                RequestDispatcher dis = request.getRequestDispatcher("./viewBook.jsp");
                dis.forward(request, response);

            } else if (action.equalsIgnoreCase("gotoCheckout")) {
                response.sendRedirect("./checkout.jsp");
            } else if (action.equalsIgnoreCase("manageBook")) {
                response.sendRedirect("./manager/manageBook.jsp");
            } else if (action.equalsIgnoreCase("manageOrder")) {
                response.sendRedirect("./manager/manageOrder.jsp");
            } else if (action.equalsIgnoreCase("manageAccount")) {
                response.sendRedirect("./manager/manageAccount.jsp");
            } else if (action.equalsIgnoreCase("")) {
                /*--------------------------------[ BOOK PROCESS ]-------------------------------*/
            } else if (action.equalsIgnoreCase("Insert")) {

                String bookTilte = request.getParameter("bTitle");
                String bookImage = request.getParameter("bImage");
                String bookAuthor = request.getParameter("bAuthor");
                String bookType = request.getParameter("bType");
                String bookPrice = request.getParameter("bPrice");


                Statement st = con.createStatement();
                String sql = "INSERT INTO Book(title, image, author, type, price) Values(" + "'" + bookTilte + "'" + ", " + "'" + bookImage + "'" + ", "
                        + "'" + bookAuthor + "'" + ", " + "'" + bookType + "'" + ", " + "'" + bookPrice + "')";
                st.executeUpdate(sql);
                response.sendRedirect("./manager/manageBook.jsp");
            } else if (action.equalsIgnoreCase("Update")) {
                RequestDispatcher dis = request.getRequestDispatcher("./manager/updateBook.jsp");
                dis.forward(request, response);

            } else if (action.equalsIgnoreCase("UpdateBook")) {//cái này là nút update trong ./manager/updateBook.jsp debug thu xem lam dc khong? h no wa roi dook
                String bID = request.getParameter("txtID");
                String bTitle = request.getParameter("txtTitle");
                String bImage = request.getParameter("txtImage");
                String bAuthor = request.getParameter("txtAuthor");
                String bType = request.getParameter("txtType");
                String bPrice = request.getParameter("txtPrice");

                Statement st = con.createStatement();
                String sql = "UPDATE Book "
                        + "SET title='" + bTitle + "',"
                            + " image='" + bImage + "',"
                            + " author='" + bAuthor + "',"
                            + " type='" + bType + "',"
                            + " price='" + bPrice + "' "
                        + "WHERE bookID='" + bID + "'";
                st.executeUpdate(sql);
                response.sendRedirect("./manager/manageBook.jsp");

            } else if (action.equalsIgnoreCase("Delete")) {
                String bookID = request.getParameter("bookIDToDelete");
                Statement st = con.createStatement();
                String sql = "DELETE from Book WHERE bookID='" + bookID + "'";
                st.executeUpdate(sql);
                response.sendRedirect("./manager/manageBook.jsp");
                /*-------------------------------[ ACCOUNT PROCESS ]-----------------------------*/

            } else if (action.equalsIgnoreCase("changeStatusUser")) {

                /*-------------------------------[ ORDER PROCESS ]-----------------------------*/
            } else if (action.equalsIgnoreCase("updateOrderStatus")) {
            } else if (action.equalsIgnoreCase("checkout")) {
                HttpSession session = request.getSession();

                ArrayList<Cart> currentCart = (ArrayList<Cart>) session.getAttribute("selectedItems");
                User curUser = (User) session.getAttribute("currentUser");
                String username = curUser.getUsername();

                if (!currentCart.isEmpty()) {
                    RequestDispatcher dis = request.getRequestDispatcher("./checkout.jsp");

                    session.setAttribute("selectedItems", this.selectedItems);
                    float totalPayment = this.getTotal(currentCart);
                    /*-------------------------[add order info to database]---------------------------------*/
                    if (Checker.insertOrderToDatabase(username, totalPayment)) {
                        out.println("<h1>Your order is placed successfully, Thanks for your support!");
                        //empty cart when user checkout complete!
                        selectedItems.clear();
                    } else {
                        out.println("<h1>There are an error when placed order! please contact admin to resolve this problem!");
                    }

                    dis.include(request, response);

                } else {
                    RequestDispatcher dis = request.getRequestDispatcher("./checkout.jsp");
                    out.println("<h1>Your cart is empty, please select product before making an order!");
                    dis.include(request, response);
                }

            } else if (action.equalsIgnoreCase("")) {
            }


        } catch (Exception ex) {
            out.println("ERROR!" + ex.getMessage());
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
